﻿using SuperSocket.ProtoBase;
using System.Buffers;

namespace SvCore.Tcp;

public class MyPackageFilter : FixedHeaderPipelineFilter<MyPackage>
{
    public MyPackageFilter()
        : base(4)
    {

    }

    protected override int GetBodyLengthFromHeader(ref ReadOnlySequence<byte> buffer)
    {
        var reader = new SequenceReader<byte>(buffer);

        reader.TryReadLittleEndian(out int len);

        return len;
    }

    protected override MyPackage DecodePackage(ref ReadOnlySequence<byte> buffer)
    {
        var package = new MyPackage();

        var reader = new SequenceReader<byte>(buffer);

        reader.Advance(4);

        reader.TryReadLittleEndian(out int pid);
        package.ProtocolId = (uint)pid;

        reader.TryReadLittleEndian(out short ecode);
        package.Ecode = ecode;

        package.Body = reader.Sequence.Slice(reader.Consumed).ToArray();

        return package;
    }
}